<template>
  <div class="anomaly-container">
	  <el-row type="flex" justify="center" class="page-header" style="margin-bottom: 30px;">
	          <el-col :span="24" class="text-center">
	              <div class="title-wrapper">
	              <i class="el-icon-search el-icon--large"></i>
	              <h1 class="main-title">水管检测信息管理系统</h1>
	              <p class="sub-title">以数据筑牢水管 “健康防线”，用检测护航用水安心，每一次细致核查，都是对民生需求的郑重回应</p>
	              </div>
	          </el-col>
	      </el-row>
    <!-- 详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="异常详情"
      width="70%"
      destroy-on-close
    >
      <el-descriptions title="异常信息" direction="vertical" :column="4" :model="anomalyDetail" border>
        <el-descriptions-item label="异常ID" :span="2">{{ anomalyDetail.anomalyId }}</el-descriptions-item>
        <el-descriptions-item label="地点ID" :span="2">{{ anomalyDetail.locationId }}</el-descriptions-item>
        <el-descriptions-item label="错误信息" :span="4">{{ anomalyDetail.errorMessage }}</el-descriptions-item>
        <el-descriptions-item label="紧急状态" :span="2">{{ anomalyDetail.urgencyStatus }}</el-descriptions-item>
        <el-descriptions-item label="处理状态" :span="2">{{ anomalyDetail.processingStatus }}</el-descriptions-item>
        <el-descriptions-item label="记录时间" :span="4">{{ formatDate(anomalyDetail.recordTime) }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 搜索和操作区 -->
    <el-row :gutter="20" style="width: 100%; margin-bottom: 20px;">
      <el-col :span="12">
        <el-input 
          placeholder="请输入地点ID或错误信息查询" 
          v-model="searchQuery" 
          style="width: 70%;"
          @keyup.enter="handleSearch"
        ></el-input>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch()" style="margin-left: 10px;">搜索</el-button>
      </el-col>
    </el-row>

    <!-- 表格部分 -->
    <el-table 
      :data="filteredData.slice((currentPage-1)*pageSize, currentPage*pageSize)" 
      border 
      style="width: 100%"
      height="450"
      :row-class-name="tableRowClassName"
    >
      <el-table-column fixed prop="anomalyId" label="编号" width="150" align="center" />
      <el-table-column prop="locationId" label="地点" width="150" align="center" />
      <el-table-column prop="errorMessage" label="错误信息" width="150" align="center" />
      <el-table-column prop="urgencyStatus" label="紧急状态" align="center" />
      <el-table-column prop="processingStatus" label="处理状态" width="140" align="center">
        <template #default="scope">
          <el-select 
            v-model="scope.row.processingStatus" 
            @change="() => updateRowStatus(scope.$index, scope.row)" 
            placeholder="处理状态"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="recordTime" label="时间" align="center" />
      <el-table-column label="操作" width="120" align="center">
        <template #default="scope">
          <div class="operation-buttons">
            <el-button type="primary" size="mini" @click="showDetail(scope.row)">详情</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-row type="flex" justify="center" style="margin-top: 20px;">
      <el-pagination 
        @size-change="handleSizeChange" 
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5,10,20,50]" 
        :page-size="pageSize" 
        :total="filteredData.length"
        layout="total, sizes, prev, pager, next, jumper"
      ></el-pagination>
    </el-row>
  </div>
</template>

<script setup>
// 修正点：添加 reactive 导入
import { ref, computed, onMounted, reactive } from 'vue'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import { post, get } from '@/utils/axios'

// 对话框控制变量
const dialogVisible = ref(false)

// 搜索和分页变量
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(5)
const tableData = ref([])

// 详情数据对象 - 使用 reactive 包装
const anomalyDetail = reactive({
  anomalyId: '',
  locationId: '',
  errorMessage: '',
  urgencyStatus: '',
  processingStatus: '',
  recordTime: ''
})

// 状态选项
const statusOptions = [
  { value: '未处理', label: '未处理' },
  { value: '处理中', label: '处理中' },
  { value: '已处理', label: '已处理' }
]

// 过滤后的数据
const filteredData = computed(() => {
  if (!searchQuery.value) return tableData.value
  const query = searchQuery.value.toLowerCase()
  return tableData.value.filter(item => 
    String(item.locationId).toLowerCase().includes(query) || 
    item.errorMessage.toLowerCase().includes(query)
  )
})

// 日期格式化
const formatDate = (dateValue) => {
  if (!dateValue) return ''
  const date = typeof dateValue === 'string' ? new Date(dateValue) : dateValue
  if (isNaN(date.getTime())) return ''
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 表格行样式
const tableRowClassName = ({ row }) => {
  const statusColorMap = { 
    '未处理': 'red-row',
    '处理中': 'yellow-row',
    '已处理': 'green-row'
  }
  return statusColorMap[row.processingStatus] || ''
}

// 打开详情对话框
const showDetail = (row) => {
  dialogVisible.value = true
  Object.assign(anomalyDetail, row)
}

// 更新状态
const updateRowStatus = (index, row) => {
  const loading = ElLoading.service({ text: '更新中...' })
  const data = {
    anomalyId: row.anomalyId,
    processingStatus: row.processingStatus
  }
  
  post('/sc/api/ano/update', data, (res) => {
    loading.close()
    if (res.status === 1) {
      ElMessage.success('状态更新成功！')
      // 更新本地数据
      tableData.value[index] = { ...row }
    } else {
      ElMessage.error(res.msg || '更新失败')
      // 恢复原状态
      row.processingStatus = tableData.value[index].processingStatus
    }
  }, (err) => {
    loading.close()
    ElMessage.error('更新失败：' + (err.message || '网络异常'))
    // 恢复原状态
    row.processingStatus = tableData.value[index].processingStatus
  })
}

// 搜索处理
const handleSearch = () => {
  if (!searchQuery.value.trim()) {
    fetchTableData()
    return
  }
  currentPage.value = 1
}

// 分页处理
const handleSizeChange = (val) => { 
  pageSize.value = val 
  currentPage.value = 1 
}
const handleCurrentChange = (val) => { 
  currentPage.value = val 
}

// 获取异常数据
const fetchTableData = () => {
  const loading = ElLoading.service({ text: '加载中...' })
  get('/sc/anomalies/byWaterCategory', {}, (res) => {
    loading.close()
    if (res.status === 1) {
      tableData.value = res.data
      ElMessage.success('数据加载成功')
    } else {
      ElMessage.error(res.msg || '获取数据失败')
    }
  }, (err) => {
    loading.close()
    ElMessage.error('加载失败：' + err.message)
  })
}

// 页面挂载时加载数据
onMounted(() => {
  fetchTableData()
})
</script>

<style scoped>
.anomaly-container {
  width: auto;
  padding: 20px;
}

/* 标题样式 */
.page-header {
  padding: 10px 0;
  border-bottom: 1px solid #e5e7eb;
}

.title-wrapper {
  display: inline-flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 8px;
}

.main-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.sub-title {
  font-size: 16px;
  color: #6b7280;
  margin: 0;
}

.el-icon--large {
  font-size: 28px;
  color: #409eff;
}

.operation-buttons {
  display: flex;
  gap: 5px;
}

.el-table .red-row {
  background-color: #ffdddd;
}

.el-table .yellow-row {
  background-color: #ffffcc;
}

.el-table .green-row {
  background-color: #ddffdd;
}

.text-right {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
</style>

